package com.hellobike.haxing.modules.pms.purchaseSend.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.system.vo.LoginUser;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.purchase.common.TimerUtil;
import com.hellobike.haxing.modules.purchase.dto.TPurchaseOrderHeadDto;
import com.hellobike.haxing.modules.purchase.entity.TPurchaseOrder;
import com.hellobike.haxing.modules.purchase.entity.TPurchaseOrderDetail;
import com.hellobike.haxing.modules.purchase.entity.TPurchasePro;
import com.hellobike.haxing.modules.purchase.enums.OrderState;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseOrderDetailService;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseOrderService;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseProService;
import com.hellobike.haxing.modules.supplier.entity.TSupplierClPro;
import com.hellobike.haxing.modules.supplier.entity.TSupplierInfo;
import com.hellobike.haxing.modules.supplier.service.ITSupplierClProService;
import com.hellobike.haxing.modules.supplier.service.ITSupplierInfoService;
import com.hellobike.haxing.modules.supplier.util.BeanUtils;
import com.hellobike.haxing.modules.wms.utils.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 采购订单表
 * @Author: haxing-boot
 * @Date:   2020-01-21
 * @Version: V1.0
 */
@RestController
@RequestMapping("/pms/purchase/tPurchaseOrder")
@Slf4j
public class TPMSPurchaseOrderController extends BaseController<TPurchaseOrder, ITPurchaseOrderService> {
	@Autowired
	private ITPurchaseOrderService tPurchaseOrderService;
	@Autowired
	private ITPurchaseProService tPurchaseProService;
	@Autowired
	private ITPurchaseOrderDetailService tPurchaseOrderDetailService;
	@Autowired
	private ITSupplierClProService tSupplierClProService;

	@Autowired
	private ITSupplierInfoService tSupplierInfoService;

	/**
	 * 分页列表查询
	 *
	 * @param tPurchaseOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "采购订单表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(TPurchaseOrder tPurchaseOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TPurchaseOrder> queryWrapper = QueryGenerator.initQueryWrapper(tPurchaseOrder, req.getParameterMap());
		Long supplierId = getSupplierId();
		if(supplierId == null){
			return Result.error("用户不存在");
		}
		queryWrapper.eq("supplier_id", supplierId);
		Page<TPurchaseOrder> page = new Page<TPurchaseOrder>(pageNo, pageSize);
		IPage<TPurchaseOrder> pageList = tPurchaseOrderService.page(page, queryWrapper);
		if(pageList != null && pageList.getTotal() > 0){
			pageList.getRecords().forEach(
					item -> {
						if(item.getPurchasePrice() != null && item.getActShippedNum() != null && item.getTotalPurchaseAmount() != null) {
							item.setTotalPurchaseAmount(item.getPurchasePrice().multiply(new BigDecimal(item.getPurchaseVolume())).toString());
						}
					}
			);
		}
		return Result.ok(pageList);
	}

	private Long getSupplierId(){
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(sysUser == null){
			return null;
		}
		QueryWrapper<TSupplierInfo> tSupplierInfoQueryWrapper = new QueryWrapper<>();
		tSupplierInfoQueryWrapper.eq("mobile", sysUser.getPhone());
		TSupplierInfo tSupplierInfo = tSupplierInfoService.getOne(tSupplierInfoQueryWrapper);
		if(tSupplierInfo == null){
			return null;
		}
		return tSupplierInfo.getId();
	}

	/**
	 *   添加
	 *
	 * @param tPurchaseOrder
	 * @return
	 */
	@AutoLog(value = "采购订单表-添加",operateType=2)
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TPurchaseOrder tPurchaseOrder) {
		tPurchaseOrderService.save(tPurchaseOrder);
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param tPurchaseOrder
	 * @return
	 */
	@AutoLog(value = "采购订单表-编辑",operateType=3)
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody TPurchaseOrder tPurchaseOrder) {
		tPurchaseOrderService.updateById(tPurchaseOrder);
		return Result.ok("编辑成功!");
	}

	/**
	 *  编辑
	 *
	 * @param tPurchaseOrder
	 * @return
	 */
	@AutoLog(value = "采购订单表-供应商采购管理修改供应量",operateType=3)
	@PutMapping(value = "/edit4OrderDetail")
	public Result<?> edit4OrderDetail(@RequestBody TPurchaseOrder tPurchaseOrder) {

		boolean res = true;
		QueryWrapper<TPurchaseOrderDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("parent_order_code", tPurchaseOrder.getOrderCode());
		List<TPurchaseOrderDetail> tPurchaseOrderDetails = tPurchaseOrderDetailService.list(queryWrapper);
		if(ListUtil.isNotEmpty(tPurchaseOrderDetails) && ListUtil.isNotEmpty(tPurchaseOrder.getTPurchaseOrderDetails())){
			for(TPurchaseOrderDetail tPurchaseOrderDetail1 : tPurchaseOrderDetails){
				for(TPurchaseOrderDetail tPurchaseOrderDetail2 : tPurchaseOrder.getTPurchaseOrderDetails()){
					if(tPurchaseOrderDetail1.getId().equals(tPurchaseOrderDetail2.getId())){
						if(tPurchaseOrder.getState().equals(OrderState.ORDER_STATE_3.getIndex()) && tPurchaseOrderDetail2.getSupplyVolume() != null && tPurchaseOrderDetail1.getSupplyVolume() != null && !tPurchaseOrderDetail1.getSupplyVolume().equals(tPurchaseOrderDetail2.getSupplyVolume())){
							res = false;
						}else{
							if(tPurchaseOrderDetail2.getSupplyVolume() != null) {
								TPurchaseOrderDetail updateDetail = new TPurchaseOrderDetail();
								updateDetail.setId(tPurchaseOrderDetail1.getId());
								updateDetail.setActShippedNum(tPurchaseOrderDetail2.getSupplyVolume());
								updateDetail.setSupplyVolume(tPurchaseOrderDetail2.getSupplyVolume());
								tPurchaseOrderDetailService.updateById(updateDetail);
							}
						}
					}
				}
			}
		}
		if(!res){
			return Result.ok("供货量已修改,请选择\"请平台审核\"!");
		}

		tPurchaseOrderService.updateById(tPurchaseOrder);
//		if(ListUtil.isNotEmpty(tPurchaseOrder.getTPurchaseOrderDetails())) {
//			tPurchaseOrder.getTPurchaseOrderDetails().forEach(
//					item ->{
//						tPurchaseOrderDetailService.updateById(item);
//					}
//			);
//		}
		return Result.ok("编辑成功!");
	}

	/**
	 *  编辑
	 *
	 * @param tPurchaseOrder
	 * @return
	 */
	@AutoLog(value = "采购订单表-生成订单",operateType=3)
	@PutMapping(value = "/genPo")
	public Result<?> genPo(@RequestBody TPurchaseOrder tPurchaseOrder) {
		tPurchaseProService.genPo(tPurchaseOrder);
		return Result.ok("编辑成功!");
	}

	/**
	 *  编辑
	 *
	 * @param
	 * @return
	 */
	@AutoLog(value = "采购订单表-获取新订单",operateType=3)
	@PostMapping(value = "/getNewPo")
	public Result<?> getNewPo() {
		TPurchaseOrderHeadDto tPurchaseOrderHeadDto = new TPurchaseOrderHeadDto();
		List<TPurchasePro> tPurchaseOrderDetailDtos = new ArrayList<>();
		tPurchaseOrderHeadDto.setTPurchaseOrderDetailDtoList(tPurchaseOrderDetailDtos);
		return Result.ok(tPurchaseOrderHeadDto);
	}

	/**
	 *  编辑
	 *
	 * @param
	 * @return
	 */
	@AutoLog(value = "采购订单表-生成订单",operateType=3)
	@PostMapping(value = "/genNewPo")
	public Result<?> genNewPo(@RequestBody TPurchaseOrderHeadDto tPurchaseOrderHeadDto) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		tPurchaseProService.genNewPo(tPurchaseOrderHeadDto,sysUser.getId());
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id生成供应商信息
	 *
	 * @param json
	 * @return
	 */
	@PostMapping(value = "/getBySupplierId")
	public Result<?> getBySupplierId(@RequestBody JSONObject json) {
		Long headerId = json.getLong("headerId");
		TPurchaseOrderHeadDto tPurchaseOrderHeadDto = new TPurchaseOrderHeadDto();
		List<TSupplierClPro> tPurchaseOrderDetailDtos = tSupplierClProService.getBySupplierId(headerId);
		List<TPurchasePro> tPurchaseOrderDetailDtoList = new ArrayList<>();
		if(ListUtil.isNotEmpty(tPurchaseOrderDetailDtos)){
			tPurchaseOrderDetailDtos.forEach(
					item -> {
						TPurchasePro tPurchasePro = new TPurchasePro();
						BeanUtils.copyProperties(item,tPurchasePro);
						tPurchaseOrderDetailDtoList.add(tPurchasePro);
					}
			);
		}
		tPurchaseOrderHeadDto.setTPurchaseOrderDetailDtoList(tPurchaseOrderDetailDtoList);
		return Result.ok(tPurchaseOrderHeadDto);
	}


	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购订单表-删除",operateType=4)
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		tPurchaseOrderService.removeById(id);
		return Result.ok("删除成功!");
	}
	/**
	 * 通过id查询
	 *
	 * @param json
	 * @return
	 */
	@PostMapping(value = "/detail")
	public Result<?> detail(@RequestBody JSONObject json) {
		String ids = json.getString("headerId");
		List<TPurchaseOrder> tPurchaseOrders = new ArrayList<>();
		QueryWrapper<TPurchaseOrder> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("order_code", ids);
		queryWrapper.last("limit 1");
		TPurchaseOrder tPurchaseOrder = tPurchaseOrderService.getOne(queryWrapper);
		if(tPurchaseOrder==null) {
			return Result.error("未找到对应数据");
		}else{
			if(tPurchaseOrder.getState() != null) {
				tPurchaseOrder.setStateStr(OrderState.getName(tPurchaseOrder.getState()));
			}
			QueryWrapper<TPurchaseOrderDetail> queryDetail = new QueryWrapper<>();
			queryDetail.in("parent_order_code", ids);
			List<TPurchaseOrderDetail> tPurchaseOrderDetails = tPurchaseOrderDetailService.list(queryDetail);
			if(ListUtil.isNotEmpty(tPurchaseOrderDetails)){
				tPurchaseOrder.setTPurchaseOrderDetails(tPurchaseOrderDetails);
				BigDecimal totalPrice = BigDecimal.ZERO;
				for(TPurchaseOrderDetail item : tPurchaseOrderDetails) {
					totalPrice = totalPrice.add(item.getPurchasePrice().multiply(new BigDecimal(item.getPurchaseVolume())));
				}
				tPurchaseOrder.setTotalPurchaseAmount(totalPrice.toString());
				if(totalPrice.compareTo(new BigDecimal(0)) == 1) {
					for(TPurchaseOrderDetail item : tPurchaseOrderDetails) {
						item.setPurchaseAmountPec(item.getPurchasePrice().multiply(new BigDecimal(item.getPurchaseVolume())).divide(totalPrice, 2).multiply(new BigDecimal(100)).toString() + "%");
					}
				}

			}
		}
		tPurchaseOrders.add(tPurchaseOrder);
		return Result.ok(tPurchaseOrders);
	}

	/**
	 * 通过id查询
	 *
	 * @param json
	 * @return
	 */
	@PostMapping(value = "/detailForPrintSku")
	public Result<?> detailForPrintSku(@RequestBody JSONObject json) {
		String ids = json.getString("headerId");
		List<TPurchaseOrder> tPurchaseOrders = new ArrayList<>();
		QueryWrapper<TPurchaseOrder> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("order_code", ids);
		queryWrapper.last("limit 1");
		TPurchaseOrder tPurchaseOrder = tPurchaseOrderService.getOne(queryWrapper);
		if(tPurchaseOrder==null) {
			return Result.error("未找到对应数据");
		}else{
			if(tPurchaseOrder.getState() != null) {
				tPurchaseOrder.setStateStr(OrderState.getName(tPurchaseOrder.getState()));
			}
			QueryWrapper<TPurchaseOrderDetail> queryDetail = new QueryWrapper<>();
			queryDetail.in("parent_order_code", ids);
			List<TPurchaseOrderDetail> tPurchaseOrderDetails = tPurchaseOrderDetailService.list(queryDetail);
			if(ListUtil.isNotEmpty(tPurchaseOrderDetails)){
				tPurchaseOrder.setTPurchaseOrderDetails(tPurchaseOrderDetails);
				BigDecimal totalPrice = BigDecimal.ZERO;
				for(TPurchaseOrderDetail item : tPurchaseOrderDetails) {
					totalPrice = totalPrice.add(item.getPurchasePrice().multiply(new BigDecimal(item.getPurchaseVolume())));

					item.setPackageDate(TimerUtil.getNowDate());
					item.setDateDue(TimerUtil.getSubDay(item.getDateDue())+"天");
				}
				tPurchaseOrder.setTotalPurchaseAmount(totalPrice.toString());
				if(totalPrice.compareTo(new BigDecimal(0)) == 1) {
					for(TPurchaseOrderDetail item : tPurchaseOrderDetails) {
						item.setPurchaseAmountPec(item.getPurchasePrice().multiply(new BigDecimal(item.getPurchaseVolume())).divide(totalPrice, 2).multiply(new BigDecimal(100)).toString() + "%");
					}
				}

			}
		}
		tPurchaseOrders.add(tPurchaseOrder);
		return Result.ok(tPurchaseOrders);
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "采购订单表-批量删除",operateType=4)
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tPurchaseOrderService.removeByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) Long id) {
		TPurchaseOrder tPurchaseOrder = tPurchaseOrderService.getById(id);
		if(tPurchaseOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(tPurchaseOrder);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param tPurchaseOrder
	 */
	@AutoLog(value = "采购订单表-导出excel",operateType=6)
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, TPurchaseOrder tPurchaseOrder) {
		return super.exportXls(request, tPurchaseOrder, TPurchaseOrder.class, "采购订单表");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@AutoLog(value = "采购订单表-导入excel",operateType=5)
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, TPurchaseOrder.class);
	}

}
